package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.NormalTableAdapter;
import com.yxt.common.ui.NormalTableAdapter.TableCell;
import com.yxt.common.ui.NormalTableAdapter.TableRow;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;  
import android.widget.ListView;
import android.widget.TextView;

public class RainIntervalCoutActivity extends Activity {
	private int[] width = { 180, 80, 50 };
	private int height = 35;
	private int color = Color.WHITE;
	private TextView lblStartTime;
	private TextView lblEndTime;
	private TextView lblInterval;
	private TextView lblMessage;
	private String starttime;
	private String endtime;
	private String drp;
	private List<Map<String,String>> stations = new ArrayList<Map<String,String>>();
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.rain_interval_count);   //软件activity的布局	
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		
		Intent intent = getIntent();
		lblStartTime = (TextView)findViewById(R.id.lblStartTime);
		lblEndTime = (TextView)findViewById(R.id.lblEndTime);
		lblInterval = (TextView)findViewById(R.id.lblInterval);
		lblMessage = (TextView)findViewById(R.id.lblMessage);
		starttime = intent.getStringExtra("starttime");
		endtime = intent.getStringExtra("endtime");
		drp = intent.getStringExtra("drp");
		lblStartTime.setText(starttime);
		lblEndTime.setText(endtime);
		lblInterval.setText(drp);
		initComponent();
	}

	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					if (stations.size() > 0) {
						fillListView();
						lblMessage.setText("分段统计结果：");
					} else {
						lblMessage.setText("没有符合条件的测站！");
					}
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadRainStation();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void downloadRainStation() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new StationCountHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}
	}

	private InputStream getInputStream() throws IOException{
		String server = CommConstant.Sever.RAIN_SERVER;		
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"raininterval.xml");
		} else {
			URL url = new URL(server + "rain/SearchCountInfo.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&starttime="+starttime+"&endtime="+endtime+"&drp="+drp);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class StationCountHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("countinfo".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				stations.add(data);
			}else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}		
	}
	
	private void fillListView() {
		List<TableRow> table = new ArrayList<TableRow>();
		String[] columns = {"name","count",""};
		for (int i = 0; i < stations.size(); i++) {
			int len = columns.length;
			TableCell[] cells = new TableCell[len];
			Map<String,String> station = stations.get(i);
			for (int j = 0; j < len; j++) {
				if (j == len - 1) {
					cells[j] = new TableCell(R.drawable.expand, width[j], height, color, TableCell.IMAGE, new ImageItemOnClickListener(station));
				} else {
					cells[j] = new TableCell(station.get(columns[j]), width[j], height, color, TableCell.STRING);
				}
			}
			table.add(new TableRow(cells));
		}
		NormalTableAdapter tableAdapter = new NormalTableAdapter(this, table);
		ListView lstWaterStation = (ListView) findViewById(R.id.lstStationList);
		lstWaterStation.setAdapter(tableAdapter);
	}
	
	private class ImageItemOnClickListener implements OnClickListener {
		Map<String,String> station;
		
		public ImageItemOnClickListener(Map<String,String> station) {
			this.station = station;
		}
		
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.putExtra("starttime", starttime);
			intent.putExtra("endtime", endtime);
			intent.putExtra("drp", drp);
			intent.putExtra("id", station.get("id"));
			intent.setClass(getApplicationContext(), RainIntervalStationsActivity.class);			
			startActivity(intent);
		}
	}
	
	protected void onDestroy() {     
        super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}